package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IPublishService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class PublishServiceImpl implements IPublishService {

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Async
    @Override
    public void createHtml(ApArticle article, String content) {
        try {
            System.out.println(Thread.currentThread().getName() + "开始执行文章静态页面任务:");
            // 通过模板引擎freemarker创建html页面
            // 获取模板
            Template template = configuration.getTemplate("article.ftl");
            // 准备数据
            Map root = new HashMap();
            root.put("content", JSON.parseArray(content));
            // 合并模板和数据
            StringWriter out = new StringWriter();
            template.process(root, out);
            // 将html页面上传到minio中
            String url = "";
            // 文章id.html
            String name = article.getId() + ".html";
            // 将StringWriter 转换成输入流
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            url = minIOService.upload(name, is, "text/html");
            // 将返回的url地址保存到文章表中
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
